package cn.edu.nuc.thrid.services.impl;

import java.sql.SQLException;

import javax.management.RuntimeErrorException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.nuc.thrid.dao.UserMapper;
import cn.edu.nuc.thrid.model.User;
import cn.edu.nuc.thrid.services.interfaces.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper mapper;

	@Override
	public User login(String username, String userpwd) {

		User user = mapper.findByUsername(username);
		if (user == null) {
			return user;
		}
		if (!user.getZybuserpwd().equals(userpwd)) {
			return null;
		}
		return user;
	}

	@Transactional(propagation = Propagation.REQUIRED, // 事务传播行为
			noRollbackFor = { NullPointerException.class }, // 当发生这些异常时,不回滚事务
			rollbackFor = { SQLException.class }, // 当发生这些异常时,回滚事务
			timeout = 20, // 超时. 当此事务耗时达到20秒时,结束此事务
			isolation = Isolation.READ_COMMITTED // 设置隔离级别。 未设置以数据库隔离级别为准
	)
	@Override
	public Integer regist(User user) {

		User u = mapper.findByUsername(user.getZybusername());

		Integer result = 0;
		if (u == null) {

			result = mapper.insertSelective(user);
		} else {

			return -1;
			// throw new RuntimeException("账号已存在，注册失败");
		}
		return result;

	}

	@Override
	public String valiname(String zybusername) {

		User user = mapper.findByUsername(zybusername);
		if (zybusername == null || "".equals(zybusername)) {
			return "NULL";
		} else if (user != null) {
			return "NO";
		} else {

			return "YES";
		}
	}

	/**
	 * 注销
	 */
	@Override
	public String logout(HttpServletRequest req, HttpServletResponse resp) {

		HttpSession session = req.getSession();

		session.removeAttribute("u");
		return null;
	}
}
